package cn.dianchiyun.protocol.netty.dtu.test1;

import cn.dianchiyun.protocol.Const;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 数据处理器
 * @author weir
 */
public class MessageHandler extends SimpleChannelInboundHandler<Object> {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void messageReceived(ChannelHandlerContext ctx, Object message) {
        logger.info("服务器发送的数据:{}", message.toString());

    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception{
        logger.info("channelActive>>>>>>>>已连接");
        super.channelActive(ctx);
        logger.info("ctx.name():"+ctx.name());
        logger.info("ctx.channel().id():"+ctx.channel().id());
        logger.info("ctx.channel().localAddress():"+ctx.channel().localAddress());
        logger.info("ctx.channel().remoteAddress():"+ctx.channel().remoteAddress());

        //ChannelManager.getInstance().addChannel(ctx.channel().remoteAddress().toString(), ctx.channel());
    }

    /**
     * 客户端关闭的处理
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.info("channelInactive>>>>>>>>已断开连接");
        super.channelInactive(ctx);
        //ChannelManager.getInstance().remove(ctx.channel());
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        logger.info("已经"+ Const.TIMEOUT+"秒未收到客户端的消息了！");
        if (evt instanceof IdleStateEvent){
            IdleStateEvent event = (IdleStateEvent)evt;
            if (event.state() == IdleState.READER_IDLE){
                logger.error("关闭这个不活跃通道！");
                ctx.channel().close();
            }
        }else {
            super.userEventTriggered(ctx, evt);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }

}
